package com.pyb.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.sql.DataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Spring相关配置(替换掉了spring-bean.xml和spring-tx.xml)
 */
@Configuration
@ComponentScan(basePackages = "com.pyb") // 如果需要扫描所有组件，可以不加过滤器
@EnableTransactionManagement // 启用事务管理器
@MapperScan("com.pyb.dao")
public class SpringConfig {

    private static final Logger logger = LoggerFactory.getLogger(SpringConfig.class);

    @Bean
    public PlatformTransactionManager transactionManager(DataSource dataSource) {
        logger.info("Initializing DataSourceTransactionManager with data source: {}", dataSource);
        try {
            DataSourceTransactionManager transactionManager = new DataSourceTransactionManager();
            transactionManager.setDataSource(dataSource);
            return transactionManager;
        } catch (Exception e) {
            logger.error("Failed to initialize DataSourceTransactionManager", e);
            throw new RuntimeException("Failed to initialize DataSourceTransactionManager", e);
        }
    }

    /**
     * 数据源配置（根据实际情况调整）
     */
    @Bean
    public DataSource dataSource() {
        org.springframework.jdbc.datasource.DriverManagerDataSource dataSource = new org.springframework.jdbc.datasource.DriverManagerDataSource();
        dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/studymysql");
        dataSource.setUsername("root");
        dataSource.setPassword("123456");
        return dataSource;
    }
    @Bean
    public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);
        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/*.xml"));
        return sessionFactory.getObject(); // 返回 SqlSessionFactory 实例
    }
}